<template>
  <div class="search-box">
    <form action="/" class="search-form">
      <van-search background="#4fc08d" v-model="searchModel" show-action placeholder="请输入搜索关键词" @search="onSearch"
        @cancel="$router.go(-1)" @focus=" isShoeResult=false" />
    </form>
    <!-- 搜索结果 -->
    <SearchResluts :value="searchModel" v-if=" isShoeResult" />
    <!-- 搜索历史 -->
    <SarchHistory :history='history' v-else-if="!searchModel" @search="onSearch" />
    <!-- 搜索推荐 -->
    <SearchRecommend v-else @search="onSearch" :value="searchModel" />
  </div>
</template>

<script>
import SarchHistory from './compontns/search-history.vue'
import SearchResluts from './compontns/search-results.vue'
import SearchRecommend from './compontns/search-recommend.vue'
import { getItem, setItem } from '../../utils/storege'
const HMTT_HISTORY = 'hmatt_history'
export default {
  components: {
    SarchHistory,
    SearchResluts,
    SearchRecommend
  },
  name: 'search',
  data () {
    return {
      history: getItem(HMTT_HISTORY) || [],
      searchModel: '',
      isShoeResult: false // 是否显示搜索结果
    }
  },
  methods: {
    // 把搜索推荐的值给文本框
    onSearch (val) {
      // this.history.findIndex(item=>{
      //   if()
      // })
      // 返回的是个新数组
      // 数组头部添加
      this.history.unshift(val)
      this.history = [...new Set(this.history)]
      this.searchModel = val
      this.isShoeResult = true
    }
  },
  watch: {
    history (val) {
      setItem(HMTT_HISTORY, val)
    }
  }

}
</script>

<style lang="less" scoped>
.search-box {
  .van-search__action {
    color: #fff;
  }
}
.search-form {
  position: sticky;
  top: 0;
  z-index: 3;
}
</style>
